//
//  129. 求根节点到叶节点数字之和.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/9/14.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation

class Solution129 {
    var sum = 0
    var preSum = 0
    func sumNumbers(_ root: TreeNode?) -> Int {
        return preOrder(root, preSum: 0)
    }
    func preOrder(_ node: TreeNode?, preSum: Int) -> Int {
        guard let node = node else {
            return 0
        }
        let sum = preSum * 10 + node.val
        if node.left == nil && node.right == nil {
            return sum
        }
        return preOrder(node.left, preSum: sum) + preOrder(node.right, preSum: sum)
    }
    static func test() {
        let solution = Solution129()
        let node1 = TreeNode(1)
        let node2 = TreeNode(2)
        let node3 = TreeNode(3)
        
        node1.left = node2
        node1.right = node3
        
        let result = solution.sumNumbers(node1)
        print(result)
    }
}
